// 和昌光谷未来城积分商城H5
// cmd 


// cmd 0 拉去用户数据
// cmd 1 推送用户填写的数据包括自己的微信信息
// cmd 2 后台账号密码登陆
// cmd 3 修改某一个用户的积分信息


var path = require('path')
var routerApi = require('../../utils/routeString.js')(__filename, __dirname);
var utils = require('../../utils/index.js')
var validate = utils.validate;
var ip = utils.ip;
var SqlHelper = utils.SqlHelper;
var jwt = require('../../utils/jwt.js')

var plusActiveIsOpen = false;


var getData = function (req, res, next) {
    var body = req.body || req.query;
    var sqlHelper = new SqlHelper('checkin_hcgg_1109');

    if (!body.openid) {
        return res.send({ code: 0, msg: '无效请求, 缺少openid' });
    }
    sqlHelper.select({ id: body.openid }, (results) => {
        if (results[0]) {
            return res.send({ code: 1, result: results[0] });
        } else {
            return res.send({ code: 0, msg: '您还未注册会员' });
        }
    })
}

var pushData = async function (req, res, next) {

    var body = req.body || req.query;
    var sqlHelper = new SqlHelper('checkin_hcgg_1109');

    if (!body.openid) {
        return res.send({ code: 0, msg: '无效请求, 缺少openid' });
    }

    if (!body.nickname || !body.headimgurl) {
        return res.send({ code: 0, msg: '无效请求, 缺少nickname, headimgurl' });
    }

    // 信息完整性检查
    if (!body.name) {
        return res.send({ code: 0, msg: '请填写姓名' });
    }
    if (!body.sex) {
        return res.send({ code: 0, msg: '请选择性别' });
    }
    if (!body.birthday) {
        return res.send({ code: 0, msg: '请填写生日' });
    }
    if (!body.phone) {
        return res.send({ code: 0, msg: '请填写手机号' });
    }
    if (!body.address) {
        return res.send({ code: 0, msg: '请填写您家庭地址' });
    }
    if (!body.family) {
        return res.send({ code: 0, msg: '请选择您家庭结构' });
    }
    // if (!body.family_birthday) {
    //     return res.send({ code: 0, msg: '请填写您的家庭成员生日' });
    // }
    if (!body.region) {
        return res.send({ code: 0, msg: '请选择您的购物区域' });
    }
    if (!body.habby) {
        return res.send({ code: 0, msg: '请选择您的兴趣爱好' });
    }
    if (!body.activity) {
        return res.send({ code: 0, msg: '请选择您喜欢的会员活动类型' });
    }

    if (!validate.isName(body.name) || !validate.isPhone(body.phone)) {
        return res.send({ code: 0, msg: '请填写正确的电话和姓名' });
    }

    var key = {
        id: body.openid
    }

 
    var data = {
        id: body.openid,
        name: body.name.toString(),
        sex: body.sex.toString(),
        birthday: body.birthday.toString(),
        phone: body.phone.toString(),
        address: body.address.toString(),
        family: body.family,
        family_birthday: body.family_birthday,
        region: body.region.toString(),
        habby: body.habby.toString(),
        activity: body.activity.toString(),
        nickname: body.nickname,
        headimgurl: body.headimgurl,
    }

    var sqlHelper = new SqlHelper('checkin_hcgg_1109');
    var result2 = await sqlHelper.asyncCount();

    sqlHelper.pushData(key, data, (state, results) => {
        return res.send({ code: state, number: result2[0].num + 1 });
    })
}

var login = async function (req, res, next) {
    var body = req.body || req.query;

    if (!body.account || !body.password) {
        return res.send({ code: 0, msg: '请输入您的账号和密码' });
    }

    if (body.account === "admin" && body.password === "hcgg123") {
        var jwtData = await jwt.encode2(body.account);
        return res.send({ code: 1, token: jwtData.token });
    } else {
        return res.send({ code: 0, msg: '账号密码错误' });
    }
}

var loginPlus = async function (req, res, next) {
    var body = req.body || req.query;

    if (!body.account || !body.password) {
        return res.send({ code: 0, msg: '请输入您的账号和密码' });
    }

    if (body.account === "admin2" && body.password === "matrix123") {
        var jwtData = await jwt.encode2(body.account);
        return res.send({ code: 1, token: jwtData.token, plusState: plusActiveIsOpen });
    } else {
        return res.send({ code: 0, msg: '账号密码错误' });
    }
}

// return {list, count, comments}
var getTableData = async function (req, res) {
    var body = req.body || req.query;
    var condition = body.condition || null;

    if (!body.token) {
        return res.send({ code: 0, msg: '账号密码错误' });
    }

    try {
        var userid = await jwt.decode(body.token);
        var sqlHelper = new SqlHelper('checkin_hcgg_1109');
        var result = await sqlHelper.asyncSelect(condition, body.offset, body.limit);
        var result2 = await sqlHelper.asyncCount() //results[0].num
        var comments = await sqlHelper.asyncComments();
        return res.send({ code: 1, result: { list: result, count: result2[0].num, comments: comments } });
    } catch (error) {
        return res.send({ code: 0, msg: error.message });
    }

}

// 更新用户积分
var updateUserInfo = async function (req, res) {
    var body = req.body || req.query;

    var point = parseInt(body.point);

    if (!body.token) {
        return res.send({ code: 0, msg: '账号密码错误' });
    }
    if (typeof body.openid != "string") {
        return res.send({ code: 0, msg: '请指定有效的用户' });
    }
    if (typeof point != "number" || isNaN(point)) {
        return res.send({ code: 0, msg: '请输入正确的数字' });
    }

    try {
        var sqlHelper = new SqlHelper('checkin_hcgg_1109');
        var results = await sqlHelper.asyncSelect({ id: body.openid });
        if (results[0]) {
            var results2 = await sqlHelper.asyncUpdate({ id: body.openid }, { point: body.point });
            return res.send({ code: 1, msg: '修改成功' });
        } else {
            return res.send({ code: 0, msg: '请指定有效的用户' });
        }
    } catch (error) {
        return res.send({ code: 0, msg: error.message });
    }

}

var plusScore = async function (req, res, score) {
    var body = req.body || req.query;
    var sqlHelper = new SqlHelper('checkin_hcgg_1109');
    var sqlHelper2 = new SqlHelper('checkin_hcgg_1109_plus');

    if (!body.openid) {
        return res.send({ code: 0, msg: '无效请求, 缺少openid' });
    }

    // 判断活动是否开始
    if (!plusActiveIsOpen) {
        return res.send({ code: 0, msg: '活动还未开始' });
    }

    // 今日时间
    var date = new Date()
    var year = date.getYear() - 100 + 2000;
    var mo = date.getMonth() + 1;
    var da = date.getDate()
    var dateStr = year.toString() + mo.toString() + da.toString();

    //判断是否是会员
    var results = await sqlHelper.asyncSelect({ id: body.openid });
    if (results[0]) {
        // 判断今天是否已经增加过
        var results2 = await sqlHelper2.asyncSelect({ openid: body.openid });
        if (results2[0]) { // 有记录
            if (results2[0].date === dateStr) {
                return res.send({ code: 0, msg: '您已经参加过活动，请下次再来。' });
            } else {
                // 增加积分
                var res5 = await sqlHelper.asyncUpdate({ id: body.openid }, { point: results[0].point + score });
                var res3 = await sqlHelper2.asyncUpdate({ openid: body.openid }, { date: dateStr });
                return res.send({ code: 1, msg: '恭喜，您已经增加了' + score + "会员积分。" });
            }
        } else { // 没有记录
            // 增加积分
            var res5 = await sqlHelper.asyncUpdate({ id: body.openid }, { point: results[0].point + score });
            var res4 = await sqlHelper2.asyncInsert({ openid: body.openid, score: "+" + score, date: dateStr });
            return res.send({ code: 1, msg: '恭喜，您已经增加了' + score + "会员积分。" });
        }
    } else {
        return res.send({ code: 0, msg: '您还未注册会员' });
    }
}

var openOrClosePlus = async function (req, res) {
    var body = req.body || req.query;

    if (!body.token) {
        return res.send({ code: 0, msg: '无权限!' });
    }
    if (!body.setState) {
        return res.send({ code: 0, msg: '无权限!' });
    }

    try {
        var userData = await jwt.decode(body.token);
        if (userData.userid === "admin2") {
            if (body.setState === "open") {
                plusActiveIsOpen = true;
                return res.send({ code: 1, msg: '活动已开启', plusState: plusActiveIsOpen });
            } else {
                plusActiveIsOpen = false;
                return res.send({ code: 1, msg: '活动已关闭', plusState: plusActiveIsOpen });
            }
        } else {
            return res.send({ code: 0, msg: '无权限!' });
        }

    } catch (error) {
        return res.send({ code: 0, msg: error.message });
    }

}

var analysisFn = function (req, res, next) {
    var body = req.body || req.query;

    var cmd = parseInt(body.cmd);

    // 命令解析
    if (isNaN(cmd)) {
        return res.send({ code: 0, msg: '无效请求, cmd参数出错' });
    }

    switch (cmd) {
        case 0:
            getData(req, res, next);
            break;
        case 1:
            pushData(req, res, next);
            break;
        case 2:
            login(req, res, next);
            break;
        case 3:
            getTableData(req, res);
            break;
        case 4:
            updateUserInfo(req, res);
            break;
        case 5: // 分数+20
            plusScore(req, res, 20);
            break;
        case 6: // 分数+30
            plusScore(req, res, 30);
            break;
        case 7: // 分数+50
            plusScore(req, res, 50);
            break;
        case 8: // 分数+70
            plusScore(req, res, 70);
            break;
        case 9: // 分数+100
            plusScore(req, res, 100);
            break;
        case 10: // 开启/关闭扫码
            openOrClosePlus(req, res);
            break;
        case 11:
            loginPlus(req, res);
            break;
        case 12: // 分数+10
            plusScore(req, res, 10);
            break;
        case 13: // 分数+1000
            plusScore(req, res, 1000);
            break;
        default:
            return res.send({ code: 0, msg: '无效请求, cmd参数出错' });
    }
}

server.post({ path: routerApi, name: routerApi }, analysisFn)